package com.smart.campus.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.smart.campus.common.config.Global;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.ServletUtils;
import com.smart.campus.common.utils.StringUtils;
import com.smart.campus.school.domain.Student;
import com.smart.campus.school.service.IStudentService;
import com.smart.campus.system.domain.SysDept;
import com.smart.campus.system.domain.SysMenu;
import com.smart.campus.system.domain.SysRole;
import com.smart.campus.system.domain.SysUser;
import com.smart.campus.system.service.ISysDeptService;
import com.smart.campus.system.service.ISysRoleService;
import com.smart.campus.system.service.ISysUserService;
import com.smart.campus.web.controller.common.JsonResultExt;
import com.smart.campus.web.core.config.WxMaConfiguration;
import com.smart.campus.web.utils.SchoolUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.ServletUtils;
import com.smart.campus.common.utils.StringUtils;

import java.util.List;

/**
 * 登录验证
 * 
 * @author 智慧校园项目组
 */
@Controller
@CrossOrigin(origins = "*",maxAge = 3600)
public class SysLoginController extends BaseController
{
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IStudentService studentService;

    //wxfb53e8c1de821a3d 个人： wx0bf63d223246901e
    String appid = "wxfb53e8c1de821a3d";

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        mmap.put("copyrightYear", Global.getCopyrightYear());
        mmap.put("env", Global.getEnvName());

        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth()
    {
        return "error/unauth";
    }

    /**
     * 绑定微信
     * @param mobile 微信获取到的手机号
     * @param openid 微信Openid
     * @return
     */
    @RequestMapping("/wechat/login")
    @ResponseBody
    public AjaxResult wechatLogin(String username, String password, @RequestParam("openid")String openid,Integer userType){

        JsonResultExt jsonResultExt=new JsonResultExt();
        if(userType != null && userType == 1){
            Student student = studentService.selectStudentByLogin(username,password);
            // 用户名或密码为空 错误
            if (student ==  null) {
                return AjaxResult.error("学号或密码错误");
            }

            Student updateStudent = new Student();
            updateStudent.setId(student.getId());
            updateStudent.setOpenId(openid);
            studentService.updateStudent(updateStudent);
            return new AjaxResult(AjaxResult.Type.SUCCESS,"登录成功",student);
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);

            SysUser user  = this.userService.selectUserByLoginName(username);
            user.setOpenId(openid);
            SysDept dept = deptService.selectDeptById(user.getDeptId());
            user.setSchoolId(SchoolUtil.getSchoolId(dept));
            this.userService.updateUserInfo(user);

            AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"登录成功",user);

            return res;
        }catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @RequestMapping("/wechat/getUserInfo")
    @ResponseBody
    public JsonResultExt getUserInfo(@RequestParam(name = "code") String code) {
        if (org.apache.commons.lang3.StringUtils.isBlank(code)) {
            JsonResultExt jsonResultExt=new JsonResultExt();
            jsonResultExt.setCode(500);
            jsonResultExt.setMessage("code不存在");
            return jsonResultExt;
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();
            String openid = session.getOpenid();
            SysUser user = this.userService.findByOpenId(openid);

            if(user == null){
                JsonResultExt jsonResultExt=new JsonResultExt();
                jsonResultExt.setCode(401);
                jsonResultExt.setData(openid);

                jsonResultExt.setMessage("微信未绑定");
                return jsonResultExt;
            }else{
                SysDept dept = deptService.selectDeptById(user.getDeptId());
                user.setSchoolId(SchoolUtil.getSchoolId(dept));
                JsonResultExt jsonResultExt=new JsonResultExt();
                jsonResultExt.setCode(200);
                jsonResultExt.setMessage("获取用户信息成功");

                jsonResultExt.setData(user);
                return jsonResultExt;
            }


        } catch (WxErrorException e) {
            JsonResultExt jsonResultExt=new JsonResultExt();
            jsonResultExt.setCode(500);
            jsonResultExt.setMessage("解析微信数据错误");
            return jsonResultExt;
        }
    }

    @RequestMapping("/wechat/getOpenId")
    @ResponseBody
    public JsonResultExt getOpenId(@RequestParam(name = "code") String code) {
        if (org.apache.commons.lang3.StringUtils.isBlank(code)) {
            JsonResultExt jsonResultExt=new JsonResultExt();
            jsonResultExt.setCode(500);
            jsonResultExt.setMessage("code不存在");
            return jsonResultExt;
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();
            String openid = session.getOpenid();
            JsonResultExt jsonResultExt=new JsonResultExt();
            jsonResultExt.setCode(200);
            jsonResultExt.setMessage("获取微信openid成功");
            jsonResultExt.setData(openid);
            return jsonResultExt;
        } catch (WxErrorException e) {
            e.printStackTrace();
            JsonResultExt jsonResultExt=new JsonResultExt();
            jsonResultExt.setCode(500);
            jsonResultExt.setMessage("解析微信openid错误");
            return jsonResultExt;
        }
    }


}
